//
//  LightController.m
//  GKBHouse
//
//  Created by  on 12-7-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LightController.h"
#import "GKBNavigationBar.h"
#import "LoginController1.h"
@implementation LightController
@synthesize equipment;
@synthesize operation;
@synthesize autoStopAnimation;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (id)initWithEquipment:(NewEquipment*)equ
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.equipment = equ;
    }
    return self;
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self.view setFrame:CGRectMake(0, 0, DEVICE_HEIGHT, DEVICE_WIDTH)];
    
    [self initTopBar];
    
    [bright setTitle:NSLocalizedString(@"bright", nil) forState:UIControlStateNormal];
    [bright addTarget:self action:@selector(goBright) forControlEvents:UIControlEventTouchUpInside];
    [stop setTitle:NSLocalizedString(@"pause", nil) forState:UIControlStateNormal];
    [stop addTarget:self action:@selector(goStop) forControlEvents:UIControlEventTouchUpInside];
    
    [dark setTitle:NSLocalizedString(@"dark", nil) forState:UIControlStateNormal];
    [dark addTarget:self action:@selector(goDark) forControlEvents:UIControlEventTouchUpInside];
    
    [OnOff addTarget:self action:@selector(ctlDevice) forControlEvents:UIControlEventTouchUpInside];
       
    if([self.equipment.state isEqualToString: kStateON])
    {
        [self setDeviceOn:YES];
    }
    else
    {
        [self setDeviceOn:NO];
    }
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
//}
- (void)initTopBar
{    
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setTarget:self returnAction:@selector(closeView) withTitle:self.equipment.name];
    [self.view addSubview:topBar];    
    [topBar release];
    
}
- (void)closeView
{
    [self stopTimer];
    [self.view removeFromSuperview];
    [GKBMainController refreshDevices];
    [GKBMainController postStartRefresh];
}
- (void)goBright
{
    [self lightOperat:@"+"];
}
- (void)goDark
{
    [self lightOperat:@"-"];
}
- (void)goStop
{
    [self lightOperat:@"S"];
}
- (void)brightAnimating
{
    mainImageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"light1.png"], [UIImage imageNamed:@"light2.png"],[UIImage imageNamed:@"light3.png"],[UIImage imageNamed:@"light4.png"],[UIImage imageNamed:@"light5.png"],nil];
    mainImageView.animationRepeatCount = -1;
    mainImageView.animationDuration = 1;
    [mainImageView startAnimating];
    
    [self setAnimationEnd:@selector(brightEnd)];
}
- (void)darkAnimating
{
    mainImageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"light5.png"], [UIImage imageNamed:@"light4.png"],[UIImage imageNamed:@"light3.png"],[UIImage imageNamed:@"light2.png"],[UIImage imageNamed:@"light1.png"],nil];
    mainImageView.animationRepeatCount = -1;
    mainImageView.animationDuration = 1;
    [mainImageView startAnimating];
    [self setAnimationEnd:@selector(darkEnd)];
}
- (void)stopAnimating
{
    [self stopTimer];
    [mainImageView stopAnimating];
}
- (void)brightEnd
{
    [self stopAnimating];
    [mainImageView setImage:[UIImage imageNamed:@"light5.png"]];
}
- (void)darkEnd
{
    [self stopAnimating];
    //[self setDeviceOn:NO];
    [mainImageView setImage:[UIImage imageNamed:@"light2.png"]];
}
- (void)setAnimationEnd:(SEL)action
{
    [self stopTimer];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self forKey:@"target"];
    [dic setValue:NSStringFromSelector(action) forKey:@"selector"];
    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:7 target:self selector:@selector(AnimationDidStop:) userInfo:dic repeats:NO];
    
    self.autoStopAnimation = time;
}
- (void)AnimationDidStop:(NSTimer *)timer
{
    NSDictionary *dic = timer.userInfo;
    id target = [dic objectForKey:@"target"];
    SEL selector = NSSelectorFromString([dic objectForKey:@"selector"]) ;
    if (target && selector) {
        [target performSelector:selector];
    }
}
- (void)stopTimer
{
    if ([self.autoStopAnimation isValid]) {
        [self.autoStopAnimation invalidate];
        self.autoStopAnimation = nil;
    }
}
- (void)operatEnd:(NSDictionary *)dic
{
    NSLog(@"%@", dic);
    NSString *result = [dic objectForKey:@"result"];

    if ([result isEqualToString:@"0"]) {//success

        if ([self.operation isEqualToString:@"+"]) {
            //[self setDeviceOn:YES];
            [self brightAnimating];
        }
        if ([self.operation isEqualToString:@"S"]) {
            [self stopAnimating];
        }
        if ([self.operation isEqualToString:@"-"]) {
            [self darkAnimating];
        }
        [self operatEndTip:YES];
    }
    if ([result isEqualToString:@"1"]) {//failure
        //
        NSLog(@"%@", result);
        [self operatEndTip:NO];
    }
    
}
- (void)lightOperat:(NSString *)operat
{
    if([self.equipment.state isEqualToString:kStateOFF])//未电器打开
    {
        NSString *pleaseOpen = NSLocalizedString(@"pleaseOpen", nil);
        [iToast showTip:pleaseOpen gravity:iToastGravityBottom];
        return;
    }
    self.operation = operat;
    NSString *orderName = @"";
    if ([self.operation isEqualToString:@"+"]) {
        orderName = NSLocalizedString(@"bright", nil);
    }
    if ([self.operation isEqualToString:@"S"]) {
        orderName = NSLocalizedString(@"pause", nil);
    }
    if ([self.operation isEqualToString:@"-"]) {
        orderName = NSLocalizedString(@"dark", nil);
    }
    NSString *operatStr = NSLocalizedString(@"operat:", nil);
    NSString *startTip = [operatStr stringByAppendingString:orderName];
    [iToast showTip:startTip gravity:iToastGravityBottom];
    
    NSString *fomate = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *switchId = self.equipment.switchId;
    NSString *sessionId = [LoginController1 sessionID];
    NSString *json = [NSString stringWithFormat:fomate, operat, switchId, sessionId];
    NSString *order = @"regulateRight";
    
    //操作失败！原因：
    NSString *errorTip = [OperationTip operatSuccess:NO type:ErrorTypeNetworkFail];
    [WebServices requestStartOrder:order body:json target:self action:@selector(operatEnd:) errorTip:errorTip];

}
- (NSString *)operatEndTipstr:(BOOL)success
{
    NSString *operat = @"";
    if ([self.operation isEqualToString:@"+"]) {
        operat = NSLocalizedString(@"bright", nil);
    }
    if ([self.operation isEqualToString:@"S"]) {
        operat = NSLocalizedString(@"pause", nil);
    }
    if ([self.operation isEqualToString:@"-"]) {
        operat = NSLocalizedString(@"dark", nil);
    }
    NSString *result = @"";
    if (success) {
        result = NSLocalizedString(@"success", nil);
    }
    else
    {
        result = NSLocalizedString(@"failure", nil);
    }
   // NSString *tip = [NSString stringWithFormat:@"%@,%@", operat, result];
    NSString *tip = @"";
    if (success) {     
        //操作成功 
        tip = [OperationTip operatSuccess:YES type:ErrorTypeServerReturnFail];
        
    }
    else
    {
        //操作失败！原因：
        tip = [OperationTip operatSuccess:NO type:ErrorTypeServerReturnFail];
       
    }
    return  tip;
}
- (void)operatEndTip:(BOOL)success
{
    NSString *tip = [self operatEndTipstr:success];
    [iToast showTip:tip gravity:iToastGravityBottom];
}
#pragma mark - 电器设备开关状态
- (void)ctlDevice
{
    NSString *switchId = self.equipment.switchId;
    NSString *name = self.equipment.name;
    BOOL STATE = [DeviceView deviceStateOn:self.equipment];
    BOOL OPEN = !STATE;
    [DeviceView OperatSwithcId:switchId name:name OnOff:OPEN target:self end:@selector(ctlDeviceEnd:)];
}
- (void)ctlDeviceEnd:(NSDictionary *)dic
{
    NSLog(@"%@", dic);
    
    NSNumber *result = [dic objectForKey:@"result"];
    NSString *resultTip = @"";
    if (result.integerValue == 0) {  
        [self stopAnimating];//停动画
        BOOL STATE = [DeviceView deviceStateOn:self.equipment ];
        BOOL OPEN = !STATE;
        //操作成功
        resultTip = [OperationTip operatSuccess:YES type:ErrorTypeServerReturnFail];
        //[DeviceView setDeivceOnOff:self.equipment button:OnOff State:OPEN];
        [self setDeviceOn:OPEN];
        
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNetTarget:self action:@selector(updateState:)];
    }
    else
    {
        //操作失败！原因：
        resultTip = [OperationTip operatSuccess:NO type:ErrorTypeServerReturnFail];
    }
    [iToast showTip:resultTip gravity:iToastGravityBottom];
   
}
- (void)updateState:(NSArray*)states
{
    [GKBMainController updateEqu:self.equipment button:OnOff states:states];
    [self setDeviceState];

}

- (void)setDeviceOn:(BOOL)on
{
    [DeviceView setDeivceOnOff:self.equipment button:OnOff State:on];
    [self setDeviceState];
}
- (void)setDeviceState
{
    if([self.equipment.state isEqualToString: kStateON])
    {
        [mainImageView setImage:[UIImage imageNamed:@"light3.png"]]; 

    }
    if([self.equipment.state isEqualToString: kStateOFF])
    {
        [mainImageView setImage:[UIImage imageNamed:@"light1.png"]]; 
    }

}
@end
